//
//  TMUserInformationController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/6/28.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMUserInformationController.h"
#import "TMUserIconController.h"
#import "TMChoicePhotosView.h"
#import "TMUserInformationModel.h"
#import "TMUserViewModel.h"
#import "TMChangePswController.h"
#import "TMVipCenterController.h"

@interface TMUserInformationController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *iocnImageView;
@property (weak, nonatomic) IBOutlet UIButton *logoutBtn;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *vipLabel;
@property (weak, nonatomic) IBOutlet UILabel *mailLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *zsCard;
@property (weak, nonatomic) IBOutlet UILabel *aliPay;
@property (weak, nonatomic) IBOutlet UILabel *wechat;
@property (weak, nonatomic) IBOutlet UILabel *weibo;
@property (weak, nonatomic) IBOutlet UITableViewCell *weboCell;
@property (weak, nonatomic) IBOutlet UITableViewCell *zsBankCell;
@property (weak, nonatomic) IBOutlet UITableViewCell *bankCell;
@property (nonatomic, copy) NSDictionary *titleDic;
@property (nonatomic, copy) NSDictionary *dataDic;
@property (nonatomic, strong) TMUserViewModel *viewModel;
@property (nonatomic, strong) TMUserSettingModel *settModel;
@property (nonatomic, strong) TMUserSettingCardsModel *setcModel;
@end

@implementation TMUserInformationController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    self.titleDic = @{@"0":@"头像",@"1":@"昵称",@"3":@"邮箱",@"4":@"手机",@"5":@"掌上生活",@"6":@"支付宝",@"7":@"微信",@"8":@"QQ"};
//    self.weboCell.hidden = YES;
    self.zsBankCell.hidden = YES;
    self.bankCell.hidden = YES;
    self.viewModel = [[TMUserViewModel alloc]init];
    [self getData];
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self getData];
//    }];
//    [self.tableView.mj_header beginRefreshing];
}
- (void)getData{
    [self.viewModel getUserSettingsDataSuccess:^(id responseObject) {
        self.settModel  = responseObject[1];
        [self displayTabWithModel:responseObject[1]];
        self.setcModel = responseObject[0];
        [self displayCardWithModel:responseObject[0]];
       // [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } failed:^(NSString *error) {
        //[self.tableView.mj_header endRefreshing];
    }];
}



- (IBAction)logoutButtonAction:(UIButton *)sender {
    UIAlertController *alert =  [UIAlertController alertControllerWithTitle:@"是否安全退出" message:nil preferredStyle:UIAlertControllerStyleAlert handler:^(UIAlertAction * _Nonnull action) {
        if ([action.title isEqualToString:@"确认"]) {
            [TMUserManager logoutSuccessed:^(id respone) {
                [TMProgressHUD showSuccessWithStyleDarkStatus:@"退出成功"];
                [TMUserManager deaufatManager].userModel.token = nil;
                 [TMUserManager deaufatManager].userModel.rongyun = nil;
                [[TMUserManager deaufatManager] updateUserModel:[TMUserManager deaufatManager].userModel];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"kUSER_INFOR_KEY"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                TMBaseTabbarContriller *nav =  [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TMBaseTabbarContriller"];
                nav.selectedIndex = 0;
                window.rootViewController = nav;
                [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
                    
                } seq:1];
            }];
        }else{
            [[SPToolSet currentViewController] dismissViewControllerAnimated:YES completion:nil];
        }
    } cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [[SPToolSet currentViewController] presentViewController:alert animated:YES completion:^{
        
    }];
}
- (void)displayTabWithModel:(TMUserSettingModel *)model{
    self.iocnImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.iocnImageView.clipsToBounds = YES;
    [self.iocnImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithBaseUrl:model.userimage]] placeholderImage:kPlaceholder];
    self.nameLabel.text = model.username;
    self.vipLabel.text = model.rank;
    if (model.mail == nil || model.mail.length == 0) {
        self.mailLabel.text = @"未绑定";
    }else{
        self.mailLabel.text = model.mail;
    }
    if (model.phone == nil ) {
        self.phoneLabel.text = @"未绑定";
    }else{
        self.phoneLabel.text = model.phone;
    }
}
- (void)displayCardWithModel:(TMUserSettingCardsModel *)model{
    
//    model.wei = @"1";
//    model.qq = @"1";
    if (model.zs_card == nil) {
        self.zsCard.text = @"未绑定";
    }else{
        self.zsCard.text = model.zs_name;
    }
    if (model.zfb_card == nil) {
        self.aliPay.text = @"未绑定";
    }else{
        self.aliPay.text = model.zfb_card;
    }
    if (model.wei.integerValue == 0) {
        self.wechat.text = @"未绑定";
    }else{
        self.wechat.text = model.band_name.wx_nickname.length?model.band_name.wx_nickname:@"已绑定";
    }
    if (model.qq.integerValue == 0) {
        self.weibo.text = @"未绑定";
    }else{
        self.weibo.text = model.band_name.qq_nickname.length?model.band_name.qq_nickname:@"已绑定";
    }
    self.dataDic = @{@"0":[NSString stringWithFormat:@"%@", self.settModel.userimage],@"1":[NSString stringWithFormat:@"%@", self.settModel.username],@"3":[NSString stringWithFormat:@"%@", self.settModel.mail],@"4":[NSString stringWithFormat:@"%@", self.settModel.phone],@"5":[NSString stringWithFormat:@"%@", self.setcModel.zs_card],@"50":[NSString stringWithFormat:@"%@", self.setcModel.zs_name],@"6":[NSString stringWithFormat:@"%@", self.setcModel.zfb_card],@"60":[NSString stringWithFormat:@"%@", self.setcModel.zfb_name],@"7":[NSString stringWithFormat:@"%@", self.setcModel.wx_card],@"70":[NSString stringWithFormat:@"%@", self.setcModel.wx_name],@"8":[NSString stringWithFormat:@"%@", self.setcModel.wb_card],@"80":[NSString stringWithFormat:@"%@", self.setcModel.wb_name]};
}
#pragma mark - Table view data source
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 0头像 1 昵称 3 邮箱 4 手机 5 6 7 8 银行卡
    if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7 || indexPath.row == 8 ) {
        NSString * title = [self.titleDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.row]];
        if ([title isEqualToString:@"微信"]) {
            
            if (self.setcModel.wei.integerValue) {
                
            }else{
                [self beginWeChatLogin];
            }
            
        }else if ([title isEqualToString:@"QQ"]){
            if (self.setcModel.qq.integerValue) {
                
            }else{
                [self beginQQLogin];
            }
        }else{
            TMUserIconController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMUserIconController"];
            vc.vcTitle = title;
            vc.information = [self.dataDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.row]];
            vc.namein = [self.dataDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.row*10]];
            [self.navigationController pushViewController:vc animated:YES];
        }
        

    }
    if (indexPath.row == 2) {
        TMVipCenterController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMVipCenterController"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 9) {
        [TMChoicePhotosView choicePhotosAddToView:self.navigationController.view withType:ChoosePhotoIVBankBind];
    }
    if (indexPath.row == 10) {
        TMChangePswController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMChangePswController"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
        
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 76;
    }
    if ( indexPath.row == 5 || indexPath.row == 9) {
        return 0;
    }
    return 54;
}
- (void)dealloc{
    
}
- (void)beginWeChatLogin{

    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id sresult, NSError *error) {
        UMSocialUserInfoResponse * info = sresult;
        NSLog(@"微信%@",info.openid);
        [self bindingRequestWithType:@"1" nickName:info.name openid:info.openid];
    }];
    
}
- (void)beginQQLogin{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:self completion:^(id sresult, NSError *error) {
        UMSocialUserInfoResponse * info = sresult;
        NSLog(@"QQ%@",info.openid);
        [self bindingRequestWithType:@"2" nickName:info.name openid:info.openid];
    }];
}
#pragma mark --NetWork Method
- (void)bindingRequestWithType:(NSString*)type nickName:(NSString*)nickName openid:(NSString*)openid{
    NSMutableDictionary *param = [TMUserManager paramDisplay];
    if (nickName.length) {
       [param setObject:nickName forKey:@"nickname"];
    }
    if (openid.length) {
        [param setObject:openid forKey:@"openid"];
    }
    if (type.length) {
        [param setObject:type forKey:@"types"];
    }
    [[TMDataRequest defaultRequest] requestWithPath:@"per/bands" parameters:param method:1 prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
        [TMProgressHUD showSuccessWithStatus:@"绑定成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              [self.navigationController popViewControllerAnimated:YES];
        });
      
        
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        NSLog(@"%@", errorMessage);

        [TMProgressHUD showErrorWithStyleDarkStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
        NSLog(@"%@", error.description);
    }];
}
@end
